<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\MemberGroup;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;

class MemberGroupController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'lv'            => 'required|integer|min:0',
        'name'          => 'required|unique:admin_group'
    ];

    /**
     * 分组管理
     * @return $this
     */
    public function getIndex()
    {
        //获取权限内的分组
        $memberGroup = MemberGroup::orderBy('lv', 'asc')
            ->paginate(15);
        return view('admin.member-group')->with(['memberGroup' => $memberGroup]);
    }

    /**
     * 添加分组
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getAdd()
    {
        return view('admin.member-group-add');
    }
    public function postAdd(Request $request)
    {
        //验证
        $this->verifyFactor['requireIntegral'] = 'integer|min:0';
        $this->verifyFactor['discount'] = 'numeric|min:0|max:10';
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            return redirect()->action('Admin\MemberGroupController@getAdd')->withInput()->withErrors($verifyMsg);
        }

        //Create
        if (MemberGroup::create($request->input()))
        {
            //setLog
            $this->setLog('create', NULL, json_encode($request->except('_token')));
            return ShowMsg('success', getLang('Tips', 'createSuccess'), action('Admin\MemberGroupController@getIndex'), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\MemberGroupController@getIndex'), 1);
    }

    /**
     * 修改分组
     * @param $id
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function getEdit($id)
    {
        $memberGroup = MemberGroup::find($id);
        if (empty($memberGroup))
            return redirect()->back();

        return view('admin.member-group-edit')->with(['memberGroup' => $memberGroup]);
    }
    public function postEdit(Request $request, $id)
    {
        //验证
        $this->verifyFactor['name'] .= ',name,'.$id;
        $this->verifyFactor['requireIntegral'] = 'integer|min:0';
        $this->verifyFactor['discount'] = 'numeric|min:0|max:10';
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            return redirect()->action('Admin\MemberGroupController@getEdit', ['id' => $id])->withErrors($verifyMsg);
        }

        //修改前的值
        $origin = MemberGroup::find($id)->toArray();
        //Update
        if (MemberGroup::where('id', $id)->update($request->except('_token')))
        {
            //setLog
            $this->setLog('update', json_encode($origin), json_encode($request->except('_token')));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\MemberGroupController@getEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\MemberGroupController@getEdit', ['id' => $id]), 1);

    }

    /**
     * 删除分组
     * @param $id
     * @return $this
     */
    public function getDel($id)
    {
        if ((int)$id === 1)
            return ShowMsg('error', getLang('Tips', 'groupNotDelete'),'',1);
        //获取用户
        $memberGroup = MemberGroup::find($id);
        $origin = $memberGroup->toArray();
        if (!empty($memberGroup))
        {
            if ($memberGroup->delete())
            {
                //setLog
                $this->setLog('delete', json_encode($origin));
                //删除分组下的用户
                User::where('type','member')->where('groupID',$id)->delete();
                return ShowMsg('success', getLang('Tips', 'deleteSuccess'),'',1);
            }
        }
        return ShowMsg('error', getLang('Tips', 'illegal'),'',1);
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'create':
                $event = [
                    'msg'   =>  'memberGroup.create',
                    'type'  =>  'Create'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'memberGroup.update',
                    'type'  =>  'Update'
                ];
                break;
            case 'delete':
                $event = [
                    'msg'   =>  'memberGroup.delete',
                    'type'  =>  'Delete'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
